<template>
  <div>
    <el-scrollbar :height="height" ref="scrollbarRef">
      <el-row style="justify-content: space-between">
        <el-form-item label="模板来源：" prop="tableName" label-width="85" style="margin-bottom: 2px !important">
          <dict-tag :options="sys_template_type" :value="propertiesForm.modelType" />
        </el-form-item>
        <el-row style="padding-top: 5px">
          <el-button size="small" type="success" @click="submitClick">保存</el-button>
        </el-row>
      </el-row>
      <el-form ref="propertiesRef" :model="propertiesForm" style="margin-top: 10px" label-width="85">
        <el-form-item label="模板名称：" prop="tableName">
          <el-input v-model="propertiesForm.tableName" placeholder="请输入模板名称" clearable />
        </el-form-item>
        <el-form-item label="模板编号：" prop="tableName">
          <el-input v-model="propertiesForm.tableCode" placeholder="请输入模板编号" clearable />
        </el-form-item>
        <el-form-item label="模板适用方案类别：" v-if="propertiesForm.tableMain === 0" prop="appTypes" label-width="126">
          <el-select v-model="propertiesForm.appTypes" placeholder="请选择" filterable style="width: 100%" multiple collapse-tags>
            <el-option v-for="dict in sys_contract_type" :key="dict.value" :label="dict.label"
              :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-radio-group v-model="propertiesForm.tableMain" @change="tableMainChange">
          <el-radio :label="0">主表</el-radio>
          <el-radio :label="1">续表</el-radio>
        </el-radio-group>
        <el-form-item label="主表模板：" prop="tableType" label-width="80" v-show="propertiesForm.tableMain == 1">
          <el-select v-model="propertiesForm.tableIds" placeholder="请选择" filterable multiple remote reserve-keyword
            remote-show-suffix :remote-method="remoteMethod2" :loading="loading6" class="custom-select1"
            style="width: 100%;">
            <el-option v-for="item in mainList" :key="item.tableId" :label="item.tableName" :value="item.tableId">
              <el-tooltip class="box-item" effect="customized" placement="right">
                <template #content>
                  {{ item.tableName }}
                </template>
                <div style="
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  ">
                  {{ item.tableName }}
                </div>
              </el-tooltip>
            </el-option>
          </el-select>
        </el-form-item>
        <el-row v-if="propertiesForm.tableMain === 0">
          <p class="pinformation">适用方法</p>
          <p class="totalStyle">共 {{ suitMethodList.length }} 条数据</p>
          <el-row style="padding-bottom: 5px; margin-left: 10px">
            <el-button link type="success" icon="plus" @click="handleAdd">新增</el-button>
          </el-row>
        </el-row>
        <el-table class="business" v-loading="loading1" :data="suitMethodList" ref="mainTableRef" max-height="70vh"
          v-if="propertiesForm.tableMain === 0">
          <el-table-column label="方法名称" align="center" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.methodCode + "　" + scope.row.methodName }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="145" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="success" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button link type="success" icon="Delete" @click="handleDel(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item label="备注：" prop="tableName" label-width="50" style="margin-top: 10px">
          <el-input :autosize="{ minRows: 3, maxRows: 7 }" type="textarea" placeholder v-model="propertiesForm.curveDesc"
            maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <div style="height: 20px"></div>
    </el-scrollbar>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="open" :title="title" width="750" @close="suitClose">
      <el-form :model="suitForm" ref="suitRef" :rules="rules" label-width="85">
        <el-form-item label="适用方法：" prop="methodId">
          <el-select v-model="suitForm.methodId" filterable remote reserve-keyword remote-show-suffix
            :remote-method="remoteMethod" :loading="loading2" style="width: 100%" @change="methodChange">
            <el-option v-for="item in methodList" :key="item.methodId" :label="item.methodCode + '　' + item.methodName"
              :value="item.methodId" :disabled="item.flagStatus == 1">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检测类别：" prop="jclbIds">
          <el-select v-model="suitForm.jclbIds" filterable multiple clearable style="width: 100%">
            <el-option v-for="item in jclbList" :key="item.jclbId" :label="item.jclbName" :value="item.jclbId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- @close="closedDialog" -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleDefine">确 定</el-button>
          <el-button type="danger" @click="open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import bus from "@/utils/eventBus";
import {
  methodToJclb,
  addMethodTable,
  editMethodTable,
  getSuitList1,
  delSuitList,
  listTableMain,
} from "@/api/templateEditor/table";
import { listMethod1 } from "@/api/store/method";
import { nextTick } from "vue";
const route = useRoute();
const { proxy } = getCurrentInstance();
const { sys_template_type } = proxy.useShareDict(
  "sys_template_type"
);
const {
  sys_contract_type,
} = proxy.useOrgDict(
  "sys_contract_type",
);
const propertiesForm = ref({});
const jclbList = ref([]);
const suitMethodList = ref([]);
const methodList = ref([]);
const mainList = ref([]);
const suitForm = ref({});
const loading = ref(false);
const loading1 = ref(false);
const loading2 = ref(false);
const loading6 = ref(false);
const open = ref(false);
const title = ref("");
const tableId = ref();
const rules = ref({
  methodId: [{ required: true, trigger: "blur", message: "适用方法不能为空" }],
});

function suitClose() {
  suitForm.value = {};
  proxy.$refs["suitRef"].clearValidate();
}

function remoteMethod2(val) {
  if (val) {
    loading6.value = true;
    setTimeout(() => {
      let temp = {
        tableMain: 0,
        tableName: val,
        params: {},
        modelType: propertiesForm.value.modelType
      };
      temp.params["filterTableId"] = tableId.value;
      listTableMain(temp).then((res) => {
        loading6.value = false;
        mainList.value = res.rows;
      });
    }, 200);
  } else {
    mainList.value = [];
  }
}

bus.off("setTableForm");
bus.on("setTableForm", (tableData) => {
  tableId.value = tableData.tableId;
  mainList.value = tableData.tableList;
  propertiesForm.value = tableData;
  getSuitData();
})

function tableMainChange(val) {
  if (val === 1) {
    delete propertiesForm.value.childTableId;
  }
}

function getSuitData() {
  nextTick(() => {
    loading1.value = true;
    getSuitList1({ tableId: tableId.value }).then((res) => {
      suitMethodList.value = res.data;
      loading1.value = false;
    });
  });
}


function handleDefine() {
  proxy.$refs.suitRef.validate((valid) => {
    if (valid) {
      if (suitForm.value.tMId) {
        editMethodTable(suitForm.value).then((res) => {
          proxy.$modal.msgSuccess("保存成功");
          open.value = false;
          getSuitData();
        });
      } else {
        addMethodTable({
          methodId: suitForm.value.methodId,
          jclbIds: suitForm.value.jclbIds,
          tableId: tableId.value,
        }).then((res) => {
          proxy.$modal.msgSuccess("保存成功");
          open.value = false;
          getSuitData();
        });
      }
    }
  });
}

function handleDel(row) {
  proxy.$modal.confirm("确定要删除吗？").then(() => {
    delSuitList(row.tMId, tableId.value).then((res) => {
      proxy.$modal.msgSuccess("删除成功");
      getSuitData();
    });
  });
}

function submitClick() {
  if (propertiesForm.value.tableMain === 1) {
    delete propertiesForm.value.appTypes
    suitMethodList.value = []
  }
  let tableData = propertiesForm.value;
  bus.emit("transferCenter", tableData);
}

bus.off("saveTransfer")
bus.on("saveTransfer", () => {
  submitClick()
})


const height = ref();

function getHeight() {
  nextTick(() => {
    height.value = proxy.getSubFileHeight(proxy, "scrollbarRef");
  });
}

function remoteMethod(val) {
  if (val) {
    loading.value = true;
    setTimeout(() => {
      listMethod1({ methodName: val }).then((res) => {
        loading.value = false;
        methodList.value = res.rows;
      });
    }, 200);
  } else {
    methodList.value = [];
  }
}

function handleAdd() {
  open.value = true;
  title.value = "新增适用方法";
}

function handleEdit(row) {
  open.value = true;
  title.value = "编辑适用方法";
  suitForm.value.methodId = row.methodId;
  suitForm.value.jclbIds = row.jclbIds;
  suitForm.value.tMId = row.tMId;

  suitForm.value.tableId = tableId.value;
  methodChange(suitForm.value.methodId)
  listMethod1({
    methodName: row.methodName,
    tableId: tableId.value,
  }).then((res) => {
    methodList.value = res.rows;
  });
}

function methodChange(val) {
  methodToJclb(val).then(res => {
    jclbList.value = res.data
  })
}

onMounted(() => {
  nextTick(() => {
    getHeight();
    window.addEventListener("resize", getHeight);
  })
})
onUpdated(() => {
  getHeight();
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getHeight);
});
</script>

<style></style>

<style lang="scss" scoped>
:deep(.el-select__tags-text) {
  max-width: 100px !important;
}
</style>